package qianfeng.com.fan_shu_xiao_bao.view.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import java.util.List;

/**
 * Created by Li_ke on 2017/1/17.
 * <p>
 * Base RecyclerView Adapter
 * 在原有的 {@link android.support.v7.widget.RecyclerView.Adapter} 适配器基类上新加了
 * </p>
 * <p>
 * 点击监听，context对象，数据源对象
 * 泛型: <数据类型,ViewHolder>
 * </p>
 */

public abstract class Base_RecyclerView_Adapter<T, VH extends Base_RecyclerView_Adapter.ViewHolder> extends RecyclerView.Adapter<VH> {
    protected Context context;
    protected List<T> datas;
    /**
     * 该RecyclerView只有在绑定时才有值
     */
    protected RecyclerView recyclerView;
    private OnItemClickListener onItemClickListener;

    public Base_RecyclerView_Adapter(Context context) {
        this.context = context;
    }

    public void setOnItemClickListener(OnItemClickListener<T,VH> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public Base_RecyclerView_Adapter(Context context, List<T> datas) {
        this.context = context;
        this.datas = datas;
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView = recyclerView;
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recyclerView = null;
    }

    @Override
    public int getItemCount() {
        return datas != null ? datas.size() : 0;
    }

    public abstract class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(onItemClickListener!=null) {
                int position = getAdapterPosition();
                onItemClickListener.onItemClick(recyclerView, v, this, position, datas.get(position));
            }
        }
    }

    public interface OnItemClickListener<T,VH extends Base_RecyclerView_Adapter.ViewHolder> {

        void onItemClick(RecyclerView parent, View view, VH holder, int position, T data);
    }
}
